package com.example.controller;

import com.example.dao.DocumentVideoOfTrainingPlanCrudRepository;
import com.example.dao.TestPaperCrudRepository;
import com.example.dao.UserCrudRepository;
import com.example.pojo.*;
import com.example.tools.JwtUtils;
import com.example.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/documentVideo")
@Slf4j
public class DocumentVideoOfPlanController {
    @Autowired
    private DocumentVideoOfTrainingPlanCrudRepository documentVideoOfTrainingPlanCrudRepository;
    @Autowired
    private UserCrudRepository userCrudRepository;

    @PostMapping("/chooseDocumentVideos")
    @Transactional
    public Result chooseDocumentVideos(@RequestBody List<Integer> ids,@RequestParam Integer trainingPlanId){
        for (Integer questionId : ids) {
            DocumentVideoOfTrainingPlan documentVideoOfTrainingPlan = new DocumentVideoOfTrainingPlan(null, trainingPlanId, questionId);
            documentVideoOfTrainingPlanCrudRepository.save(documentVideoOfTrainingPlan);
        }
        return Result.success();
    }
    @PostMapping("/unchooseDocumentVideos")
    @Transactional
    public Result unchooseDocumentVideos(@RequestBody List<Integer> ids,@RequestParam Integer trainingPlanId){
        
        for (Integer questionId : ids) {
            documentVideoOfTrainingPlanCrudRepository.deleteByDocumentVideoIdAndTrainingPlanId(questionId,trainingPlanId);
        }
        return Result.success();
    }


    @GetMapping("/getDocumentVideo")
    public Result getDocumentVideo(Integer trainingPlanId,Integer choose, @RequestHeader("token") String token){
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        log.info("trainingPlanId,{}",trainingPlanId);

        List<DocumentVideo> documentVideos = new ArrayList<>();
        if (choose == 0) {
            documentVideos.addAll(documentVideoOfTrainingPlanCrudRepository.unselectedDocumentVideo(trainingPlanId,user.getAgencyId()));
        } else {
            documentVideos.addAll(documentVideoOfTrainingPlanCrudRepository.selectedDocumentVideo(trainingPlanId));
        }


        return Result.success(documentVideos);
    }



}
